package cn.wgx.safetyhelmet.service.imp;

import cn.wgx.safetyhelmet.entity.User;
import cn.wgx.safetyhelmet.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;

import java.util.List;


@Service
public class UserServiceJdbcImp implements UserService {

    @Autowired
    JdbcTemplate jdbcTemplate;

    @Override
    public List getUsers(User user) {
        return jdbcTemplate.queryForList("select * from sys_user");
    }

    @Override
    public User add(User user) {
        int n = jdbcTemplate.update("insert into sys_user(name,age) values(?,?)", user.getName(), user.getAge());
        return user;
    }

    @Override
    public int del(Long id) {
        return jdbcTemplate.update("delete from sys_user where id=?", id);
    }

    @Override
    public int del(String name) {
        return jdbcTemplate.update("delete from sys_user where [name]=?", name);
    }

    @Override
    public int update(User user) {
        return jdbcTemplate.update("update table sys_user set name=?,age=? where id=?", user.getName(), user.getAge(),user.getId());
    }

    @Override
    public int getAllUsers() {
        return jdbcTemplate.queryForObject("select count(1) from sys_user", Integer.class);
    }

    @Override
    public User getUserById(Long id) {
        return jdbcTemplate.queryForObject("select * from sys_user where id = ?", (rs, rowNum) -> {
            User user = new User();
            user.setId(rs.getLong("id"));
            user.setName(rs.getString("name"));
            user.setAge(rs.getInt("age"));
            user.setSex(rs.getInt("sex"));
            user.setBirthday(rs.getTimestamp("birthday"));
            return user;
        }, id);
    }
}
